package test.udp.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPServer {
	public static void main(String args[]) {
		try {
			// 创建Socket
			DatagramSocket socket = new DatagramSocket(12345);

			// 创建接收包
			byte buf[] = new byte[1000];
			DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
			System.out.println("开始接收包");

			// 循环监听
			while (true) {
				socket.receive(receivePacket);
				String name = receivePacket.getAddress().toString();
				System.out.println("来自主机：" + name + "\n端口："
						+ receivePacket.getPort());
				String s = new String(receivePacket.getData(), 0, receivePacket
						.getLength());
				System.out.println("接收数据：" + s);
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
